package com.btb.adapter.service;

import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.ExecutionException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.web3j.abi.FunctionEncoder;
import org.web3j.abi.datatypes.Function;
import org.web3j.abi.datatypes.Uint;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.RawTransaction;
import org.web3j.crypto.TransactionEncoder;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.tx.gas.DefaultGasProvider;
import org.web3j.utils.Numeric;

@Service
public class AccountService {

	@Value("${adapter.contract.buy.address}")
	private String contractBuyAddress;
	@Autowired
	private Credentials credentials;
	@Autowired
	private Web3j web3j;

	private BigInteger getNonce(String address) throws Exception {
		EthGetTransactionCount ethGetTransactionCount = web3j
				.ethGetTransactionCount(address, DefaultBlockParameterName.LATEST).sendAsync().get();
		return ethGetTransactionCount.getTransactionCount();
	}

	public void buy(String orderId, int type, long orderTotalPrice) {
		Function function = new Function("setCompleted", Arrays.asList(new Uint(new BigInteger("100"))),
				Collections.emptyList());
		try {
			BigInteger nonce = getNonce(credentials.getAddress());
			String encodeFunction = FunctionEncoder.encode(function);
			BigInteger gasLimit = new BigInteger("300000");
			RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, DefaultGasProvider.GAS_PRICE,
					gasLimit, contractBuyAddress, encodeFunction);
			EthSendTransaction response = web3j
					.ethSendRawTransaction(
							Numeric.toHexString(TransactionEncoder.signMessage(rawTransaction, credentials)))
					.sendAsync().get();
			String transactionHash = response.getTransactionHash();
			System.out.println(transactionHash);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
